//
//  userAccount.swift
//  WeiBo_Private
//
//  Created by Yangperlove on 16/1/12.
//  Copyright © 2016年 Yangperlove. All rights reserved.
//

import UIKit

class UserAccount: NSObject,NSCoding {
    //用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    //access_token的生命周期，单位是秒数。
    var expires_in: NSTimeInterval = 0 {
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //access_token的生命周期（该参数即将废弃，开发者请使用expires_in）。
    var remind_in: String?
    //当前授权用户的UID。
    var uid: String?
    //友好显示名称
    var name: String?
    //用户头像地址（大图），180×180像素
    var avatar_large: String?
    //获取过期时间
    var expires_date: NSDate?
    
    
    
    //字典转模型对象
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    //重写对象的描述信息
    override var description: String {
        //使用kvc方式 获取对象 的字典信息
        let keys = ["access_token","expires_in","uid","remind_in","name","avatar_large"]
        let dict = self.dictionaryWithValuesForKeys(keys)
        return dict.description
    }
    
    func saveUserAccount() {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    class func getUserAccount() -> UserAccount? {
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!.stringByAppendingString("/userAccount.plist")
        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? UserAccount{
            if account.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
                return account
            }
        }
        return nil
    }
    
    //将二进制->对象
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        //如果是基本数据类型 可以直接 解归档到具体类型
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    //将对象->二进制
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(expires_date, forKey: "expires_date")
    }
    
}
